<?php
/**
 * Created By PhpStorm
 * Author: patrick wu
 * Date: 2020/12/7
 * Time: 14:05
 */
namespace App\Http\Controllers\Api;

use App\Service\Live\OperateService;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Jenssegers\Mongodb\Eloquent\Model;

class Product extends Model
{
    protected $connection   =   'mongodb';

    protected $collection   =   'product';

    protected $guarded  =   [];

    public $timestamps  =   false;
}

class MoveController extends BaseController
{
    public function moveCate()
    {
        $total = DB::connection('mysql_sass')->table('cz_shop_custom_type')->select()->get()->each(function (&$item) {
            /*$category['unique_id']  =   $item->Id;
            $category['shop_id']    =   1;
            $category['cat_name']   =   $item->Name;
            $category['cat_pic']    =   '';
            $category['cat_icon']   =   '';
            $category['parent_id']  =   1;
            $category['level']      =   1;
            $category['sorting']    =   $item->SortOrder;
            $category['ad_pic']     =   '';
            $category['ad_url']     =   '';
            $category['is_shelf']   =   1;
            $category['is_delete']  =   0;
            $category['delete_time']=   0;
            $category['created_at'] =   Carbon::now()->timestamp;
            $category['updated_at'] =   Carbon::now()->timestamp;
            DB::table('mini_category')->insert($category);*/
            $info = DB::table('mini_category')->where(['unique_id' => $item->ParentId])->select('id', 'level')->first();
            if (empty($info)) {
                DB::table('mini_category')->where(['unique_id' => $item->Id])->update([
                    'parent_id' => 0,
                    'level' => 1
                ]);
                return;
            }

            DB::table('mini_category')->where(['unique_id' => $item->Id])->update([
                'parent_id' => $info->id,
                'level' => $info->level + 1
            ]);

        });
        dd(count($total));
    }

    public function moveBoxOwner()
    {
        $total = DB::connection('mysql_sass')->table('cz_box_owner')->get()->each(function ($item) {
            /*$owner['unique_id'] =   $item->Id;
            $owner['user_id']   =   100000;
            $owner['name']      =   $item->Name ?? '';
            $owner['nick_name'] =   $item->NickName ?? '';
            $owner['phone']     =   $item->Mobile ?? '';
            $owner['level']     =   $item->Level ?? 1;
            $owner['box_count'] =   $item->BoxCount ?? 0;
            $owner['parent_id'] =   0;
            $owner['desc']      =   $item->Desc ?? '';
            $owner['created_at']=   Carbon::now()->timestamp;
            $owner['updated_at']=   Carbon::now()->timestamp;
            DB::table('mini_box_owner')->insert($owner);*/
            $info = DB::table('mini_box_owner')->where(['unique_id' => $item->ParentOwnerId])->select('id')->first();
            if (empty($info)) {
                DB::table('mini_box_owner')->where(['unique_id' => $item->Id])->update([
                    'parent_id' => 0,
                ]);
                return;
            }

            DB::table('mini_box_owner')->where(['unique_id' => $item->Id])->update([
                'parent_id' => $info->id,
            ]);
        });

        dd(count($total));
    }

    public function moveBox()
    {
        $total = DB::connection('mysql_sass')->table('cz_box')->get()->each(function ($item) {
            $owner['unique_id'] =   $item->Id;
            $owner['box_name']  =   $item->BoxName;
            $owner['box_code']  =   $item->Code ?? '';
            $owner['user_id']   =   0;
            $owner['owner_id']  =   DB::table('mini_box_owner')->where(['unique_id' => $item->OwnerId])->value('id') ?? 0;
            $owner['parent_id'] =   0;
            $owner['area_id']   =   0;
            $owner['remark']    =   $item->Remark ?? '';
            $owner['is_delete'] =   0;
            $owner['delete_time']=  0;
            $owner['created_at']=   Carbon::now()->timestamp;
            $owner['updated_at']=   Carbon::now()->timestamp;
            DB::table('mini_box')->insert($owner);
            /*$info = DB::table('mini_box')->where(['unique_id' => $item->ParentOwnerId])->select('id')->first();
            if (empty($info)) {
                DB::table('mini_box')->where(['unique_id' => $item->Id])->update([
                    'parent_id' => 0,
                ]);
                return;
            }

            DB::table('mini_box')->where(['unique_id' => $item->Id])->update([
                'parent_id' => $info->id,
            ]);*/
        });

        dd(count($total));
    }

    public function moveAttribute()
    {
        $total = DB::connection('mysql_sass')->table('cz_shop_specification')->get()->each(function ($item) {
            $attr['attr_name']  =   $item->Name;
            $attr['attr_en_name']=  $item->ColumnName;
            $attr['sorting']   =  $item->SortOrder;
            $attr['shop_id']   =  1;
            $attr['is_system'] =  1;
            $attr['is_delete'] =  0;
            $attr['created_at']=  Carbon::now()->timestamp;
            $attr['updated_at']=  Carbon::now()->timestamp;
            DB::table('mini_attribute')->insert($attr);
        });

        dd(count($total));
    }

    public function moveSupply()
    {
        $total = DB::connection('mysql_sass')->table('cz_shop_supplier')->get()->each(function ($item) {
            $supply['unique_id']  =  $item->Id;
            $supply['shop_id']    =  1;
            $supply['supply_name']=  $item->Name;
            $supply['supply_desc']=  $item->Description;
            $supply['sorting']    =  $item->SortOrder ?? 0;
            $supply['is_delete']  =  0;
            $supply['delete_time']=  0;
            $supply['created_at'] =  Carbon::now()->timestamp;
            $supply['updated_at'] =  Carbon::now()->timestamp;
            DB::table('mini_supply')->insert($supply);
        });

        dd(count($total));
    }

    public function moveKeyword()
    {
        $total = DB::connection('mysql_sass')->table('czfw_search_keywords')->get()->each(function ($item) {
            $keyword['shop_id']   =   1;
            $keyword['keyword']   =   $item->Keywords;
            $keyword['sorting']   =   $item->SortOrder;
            $keyword['created_at']=   Carbon::now()->timestamp;
            $keyword['updated_at']=   Carbon::now()->timestamp;
            DB::table('mini_hot_keyword')->insert($keyword);
        });

        dd(count($total));
    }

    public function moveBrand()
    {
        $total = DB::connection('mysql_sass')->table('cz_shop_brand')->get()->each(function ($item) {
            $brand['shop_id']   =   1;
            $brand['unique_id'] =   $item->Id;
            $brand['brand_name']=   $item->Name;
            $brand['brand_logo']=   $item->Logo;
            $brand['brand_pic'] =   $item->Image;
            $brand['brand_icon']=   $item->Icon;
            $brand['brand_desc']=   $item->Description;
            $brand['sorting']   =   $item->SortOrder;
            $brand['is_delete'] =   0;
            $brand['delete_time']=  0;
            $brand['created_at']=   Carbon::now()->timestamp;
            $brand['updated_at']=   Carbon::now()->timestamp;
            DB::table('mini_brand')->insert($brand);
        });

        dd(count($total));
    }

    public function moveProduct()
    {
        $total = DB::connection('mysql_sass')->table('cz_shop_product_base')->get()->each(function ($item) {
//            dd($item);
            $good['unique_id']  =   $item->Id;
            $good['mini_id']    =   1;
            $good['shop_id']    =   1;
            $good['supply_id']      =   DB::table('mini_supply')->where(['unique_id' => $item->SupplierId])->value('id') ?? 0;
            $good['brand_id']       =   DB::table('mini_brand')->where(['unique_id' => $item->BrandId])->value('id') ?? 0;
            $good['name']           =   $item->Name;
            $good['sku_code']       =   $item->Code ?? '';
            $good['sell_price']     =   ($item->Price ?? 0) / 100;
            $good['original_price'] =   ($item->TagPrice ?? 0) / 100;
            $good['cost_price']     =   ($item->SupplyPrice ?? 0) / 100;
            $good['is_shelf']       =   1;
            $good['is_hot']         =   1;
            $good['is_member']      =   0;
            $good['is_connection']  =   0;
            $good['cover_pic']      =   $item->MainImage ?? '';
            $good['cover_video']    =   '';
            $good['virtual_sales']  =   $item->InitialSale ?? 0;
            $good['real_sales'] =   $item->Sale ?? 0;
            $good['sorting']    =   $item->SortOrder;
            $good['stock']      =   $item->Stock ?? 0;
            $good['reduce_type']=   $item->StockReduceMethod ?? 1;
            $good['unit']       =   '';
            $good['weight']     =   0;
            $good['freight']    =   0;
            $good['limit_number']=  $item->MaxBuyableCount ?? 0;
            $good['desc']        =   $item->Summary ?? '';
            $good['spec_remark']        =   '';
            $good['detail']             =   $item->Description ?? '';
            $good['is_commission']      =   1;
            $good['is_box_commission']  =   0;
            $good['is_auto_send']=   0;
            $good['version']     =   createUniqueID();
            $good['is_delete']   =   0;
            $good['delete_time'] =   0;
            $good['created_at']  =   Carbon::now()->timestamp;
            $good['updated_at']  =   Carbon::now()->timestamp;
            DB::beginTransaction();
            try {
                $good_id    =   DB::table('mini_product')->insertGetId($good);
                $cat['product_id']  =   $good_id;
                $cat_id     =   DB::connection('mysql_sass')->table('cz_shop_product_type')->where(['ProductId' => $item->Id])->value('TypeId');
                $cat['cat_id']      =   DB::table('mini_category')->where(['unique_id' => $cat_id])->value('id') ?? 0;
                $cat['created_at']  =   Carbon::now()->timestamp;
                $cat['updated_at']  =   Carbon::now()->timestamp;
                DB::table('mini_product_cat')->insert($cat);
                DB::commit();
            } catch (\Exception $e) {
                dd($e->getMessage());
                DB::rollBack();
            }
        });

        dd(count($total->toArray()));
    }

    public function moveDetail()
    {
        $result =   Product::query()->select()->offset(0)->limit(4000)->get()->each(function ($item) {
            $good_info  =   DB::table('mini_product')->where(['unique_id' => $item->_id])->select(['id', 'unique_id', 'name'])->first();
            if (empty($good_info)) {
                return;
            }
//            dd(json_encode($item->detail['images'], JSON_UNESCAPED_UNICODE));
            DB::beginTransaction();
            try {
                /**
                 * 保存图片
                 */
                $total_image    =   [];
                if (!empty($item->baseInfo['topImages'])) {
                    foreach ($item->baseInfo['topImages'] as $images) {
                        $single['product_id']   =   $good_info->id;
                        $single['object_url']   =   $images;
                        $single['object_type']  =   1;
                        $single['is_delete']    =   0;
                        $single['created_at']   =   $single['updated_at']   =   Carbon::now()->timestamp;
                        $total_image[]          =   $single;
                    }
                }

                if (!empty($total_image)) {
                    DB::table('mini_product_object_url')->insert($total_image);
                }

                /**
                 * 修改封面图和详情
                 */
                DB::table('mini_product')->where(['id' => $good_info->id])->update([
                    'cover_pic' =>  $item->baseInfo['cover'],
                    'cover_video' =>  $item->baseInfo['video'],
                    'detail'  =>    json_encode($item->detail['images'], JSON_UNESCAPED_UNICODE),
                ]);

                /**
                 * 添加规格
                 */
                $total_spec =   [];
                if (!empty($item->skuInfo['skus'])) {
                    foreach ($item->skuInfo['skus'] as $key => $sku) {
                        $attr_value =   [];
                        if (!empty($item->skuInfo['skuAttrs'])) {
                            foreach ($item->skuInfo['skuAttrs'] as $attr => $value) {
                                $attr_value[$value] =   $sku[$attr];

                                //添加属性
                                if (!DB::table('mini_attribute')->where(['attr_name' => $value, 'attr_en_name' => $attr])->exists()) {
                                    $mini_attr['attr_name'] =   $value;
                                    $mini_attr['attr_en_name']  =   $attr;
                                    $mini_attr['is_system'] =   0;
                                    $mini_attr['sorting']   =   rand(1, 9999);
                                    $mini_attr['is_delete'] =   0;
                                    $mini_attr['created_at']=   $mini_attr['updated_at']    =   Carbon::now()->timestamp;
                                    DB::table('mini_attribute')->insert($mini_attr);
                                }

                                //添加属性值
                                $attr_id    =   DB::table('mini_attribute')->where(['attr_name' => $value, 'attr_en_name' => $attr])->value('id');
                                if ($attr_id) {
                                    if (!DB::table('mini_attribute_value')->where(['attr_id' => $attr_id, 'attr_name' => $value, 'attr_value' => $sku[$attr]])->exists()) {
                                        $mini_value['attr_id']   =   $attr_id;
                                        $mini_value['attr_name'] =   $value;
                                        $mini_value['attr_value']=   $sku[$attr];
                                        $mini_value['is_default']=   0;
                                        $mini_value['is_delete'] =   0;
                                        $mini_value['created_at']=   $mini_value['updated_at']    =   Carbon::now()->timestamp;
                                        DB::table('mini_attribute_value')->insert($mini_value);
                                    }
                                }

                            }
                        }

                        $spec['attr_list']  =   json_encode($attr_value, JSON_UNESCAPED_UNICODE);
                        $spec['product_id'] =   $good_info->id;
                        $spec['sku_code']   =   $sku['code'] ?? '';
                        $spec['spec_pic']   =   $sku['img'] ?? '';
                        $spec['stock']      =   $sku['stock'] ?? 0;
                        $spec['sell_price'] =   ($sku['price'] ?? 0) / 100;
                        $spec['cost_price'] =   ($sku['cost_price'] ?? 0) / 100;
                        $spec['original_price'] =   ($sku['tagPrice'] ?? 0) / 100;
                        $spec['created_at'] =   $spec['updated_at'] =   Carbon::now()->timestamp;
                        $total_spec[]   =   $spec;
                    }
                }

                DB::table('mini_product_specs')->insert($total_spec);
                DB::commit();
            } catch (\Exception $e) {
                dump($e->getMessage());
                DB::rollBack();
            }
        });
        dd(count($result->toArray()));
    }

    public function moveShare()
    {
        $total = DB::connection('mysql_sass')->table('cz_shop_distribution_product')->get()->each(function ($item) {
//            dd($item);
            $product_id =   DB::table('mini_product')->where(['unique_id' => $item->ProductId])->value('id');
            if (empty($product_id)) {
                return;
            }
            $commission['product_id']       =   $product_id;
            $commission['commission_price'] =   0;
            $commission['commission_rate']  =   $item->FirstRate ?? 0;
            $commission['invite_rate']      =   $item->SecondRate ?? 0;
            $commission['self_rate']        =   $item->SelfPurchaseRate ?? 0;
            $commission['first_rate']       =   $item->ClientOneStarRate ?? 0;
            $commission['second_rate']      =   $item->ClientTwoStarRate ?? 0;
            $commission['third_rate']       =   $item->ClientThreeStarRate ?? 0;
            $commission['is_commission']    =   $item->Participated ? 1 : 0;
            $commission['is_box_commission']=   $item->ParticipatedClient ? 1 : 0;
            $commission['is_default']       =   0;
            $commission['is_box_default']   =   0;
            $commission['is_delete']        =   0;
            $commission['delete_time']      =   0;
            $commission['created_at']       =   Carbon::now()->timestamp;
            $commission['updated_at']       =   Carbon::now()->timestamp;
            DB::table('mini_product_commission')->insert($commission);
        });

        dd(count($total->toArray()));
    }

    public function moveGoodCat()
    {
        $total = DB::connection('mysql_sass')->table('cz_shop_product_type')->select(['ProductId', 'TypeId'])->get()->each(function ($item) {
            DB::beginTransaction();
            try {
                $cat['cat_id']      =   DB::table('mini_category')->where(['unique_id' => $item->TypeId])->value('id') ?? 0;
                $cat['product_id']      =   DB::table('mini_product')->where(['unique_id' => $item->ProductId])->value('id') ?? 0;
                $cat['created_at']  =   Carbon::now()->timestamp;
                $cat['updated_at']  =   Carbon::now()->timestamp;
                DB::table('mini_product_cat')->insert($cat);
                DB::commit();
            } catch (\Exception $e) {
                dd($e->getMessage());
                DB::rollBack();
            }
        });

        dd(count($total->toArray()));
    }
}
